package com.dhcc.core.framework.security.filter;

import org.pac4j.core.context.ContextHelper;
import org.pac4j.core.context.HttpConstants;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.http.url.UrlResolver;

/**
 * 地址匹配器
 */
public class Pac4jUrlResolver implements UrlResolver {


    public Pac4jUrlResolver() {
    }

    @Override
    public String compute(final String url, WebContext context) {

        final boolean relativeUrl = url != null
            && !url.startsWith(HttpConstants.SCHEME_HTTP) && !url.startsWith(HttpConstants.SCHEME_HTTPS);

        if (context != null && relativeUrl) {
            final StringBuilder sb = new StringBuilder();

            sb.append(context.getScheme()).append("://").append(context.getServerName());

            final boolean notDefaultHttpPort = ContextHelper.isHttp(context) &&
                context.getServerPort() != HttpConstants.DEFAULT_HTTP_PORT;
            final boolean notDefaultHttpsPort = ContextHelper.isHttps(context) &&
                context.getServerPort() != HttpConstants.DEFAULT_HTTPS_PORT;
            if (notDefaultHttpPort || notDefaultHttpsPort) {
                sb.append(":").append(context.getServerPort());
            }

            sb.append(url.startsWith("/") ? url : "/" + url);
            return sb.toString();
        }

        return url;
    }
}
